
import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { 
  TestTube, 
  Play, 
  CheckCircle, 
  AlertCircle,
  Clock,
  Zap
} from "lucide-react";
import { InvokeLLM as base44InvokeLLM } from "@/api/integrations";

export default function ConfigTestPanel({ llmConfigs }) {
  const [selectedConfig, setSelectedConfig] = useState("");
  const [testPrompt, setTestPrompt] = useState("请简单介绍一下您的功能和能力。");
  const [testResult, setTestResult] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  const handleTest = async () => {
    if (!selectedConfig || !testPrompt.trim()) {
      alert("请选择配置并输入测试提示词");
      return;
    }

    setIsLoading(true);
    setTestResult(null);
    
    const startTime = Date.now();
    
    try {
      const config = llmConfigs.find(c => c.id === selectedConfig);
      if (!config) {
        throw new Error("配置不存在");
      }

      // 调用测试函数
      const response = await testLLMConfig(config, testPrompt);
      const duration = Date.now() - startTime;
      
      setTestResult({
        success: true,
        response: response,
        duration: duration,
        config: config
      });
    } catch (error) {
      const duration = Date.now() - startTime;
      setTestResult({
        success: false,
        error: error.message,
        duration: duration,
        config: llmConfigs.find(c => c.id === selectedConfig)
      });
    } finally {
      setIsLoading(false);
    }
  };

  const testLLMConfig = async (config, prompt) => {
    // 如果是Base44自带模型，则真实调用
    if (config.config_value.provider === 'base44') {
      try {
        const response = await base44InvokeLLM({ prompt });
        const responseText = typeof response === 'object' ? JSON.stringify(response, null, 2) : response;
        return {
          text: `来自 ${config.config_value.model} 的测试响应: ${responseText}`,
          // Base44集成不返回token用量，这里模拟一个结构
          usage: {
            prompt_tokens: 'N/A',
            completion_tokens: 'N/A',
            total_tokens: 'N/A'
          }
        };
      } catch (e) {
        throw new Error(`调用Base44内置模型失败: ${e.message}`);
      }
    }
    
    // 对于其他第三方模型，仍然使用模拟响应
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (config.config_value.api_key && config.config_value.api_key.length > 5) { // 模拟API Key验证
          resolve({
            text: `[模拟响应] 这是来自 ${config.config_value.model} 的测试响应。您的提示词是："${prompt}"。我是一个AI助手，可以帮助您处理各种任务。`,
            usage: {
              prompt_tokens: Math.round(prompt.length / 4),
              completion_tokens: 50,
              total_tokens: Math.round(prompt.length / 4) + 50
            }
          });
        } else {
          reject(new Error("模拟的API错误：API密钥无效或过短。"));
        }
      }, 800 + Math.random() * 1000);
    });
  };

  return (
    <div className="space-y-6">
      <Card className="shadow-lg border-0">
        <CardHeader className="bg-gradient-to-r from-purple-50 to-pink-50 border-b">
          <CardTitle className="flex items-center gap-2">
            <TestTube className="w-5 h-5 text-purple-600" />
            配置测试面板
          </CardTitle>
        </CardHeader>
        <CardContent className="p-6">
          <div className="space-y-6">
            <div>
              <Label htmlFor="config_select">选择要测试的大模型配置</Label>
              <Select value={selectedConfig} onValueChange={setSelectedConfig}>
                <SelectTrigger>
                  <SelectValue placeholder="请选择配置" />
                </SelectTrigger>
                <SelectContent>
                  {llmConfigs.map((config) => (
                    <SelectItem key={config.id} value={config.id}>
                      <div className="flex items-center gap-2">
                        <span>{config.configKey}</span>
                        {config.isDefault && (
                          <Badge className="bg-yellow-100 text-yellow-700 text-xs">默认</Badge>
                        )}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="test_prompt">测试提示词</Label>
              <Textarea
                id="test_prompt"
                value={testPrompt}
                onChange={(e) => setTestPrompt(e.target.value)}
                placeholder="输入您想要测试的提示词..."
                rows={4}
              />
            </div>

            <div className="flex justify-center">
              <Button
                onClick={handleTest}
                disabled={isLoading || !selectedConfig || !testPrompt.trim()}
                className="bg-purple-600 hover:bg-purple-700"
              >
                {isLoading ? (
                  <>
                    <Clock className="w-4 h-4 mr-2 animate-spin" />
                    测试中...
                  </>
                ) : (
                  <>
                    <Play className="w-4 h-4 mr-2" />
                    开始测试
                  </>
                )}
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Test Results */}
      {testResult && (
        <Card className="shadow-lg border-0">
          <CardHeader className={`border-b ${testResult.success ? 'bg-green-50' : 'bg-red-50'}`}>
            <CardTitle className="flex items-center gap-2">
              {testResult.success ? (
                <>
                  <CheckCircle className="w-5 h-5 text-green-600" />
                  <span className="text-green-800">测试成功</span>
                </>
              ) : (
                <>
                  <AlertCircle className="w-5 h-5 text-red-600" />
                  <span className="text-red-800">测试失败</span>
                </>
              )}
            </CardTitle>
          </CardHeader>
          <CardContent className="p-6">
            <div className="space-y-4">
              {/* Test Info */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 p-4 bg-gray-50 rounded-lg">
                <div>
                  <div className="text-sm text-gray-500">配置</div>
                  <div className="font-medium">{testResult.config?.configKey}</div>
                </div>
                <div>
                  <div className="text-sm text-gray-500">模型</div>
                  <div className="font-medium">{testResult.config?.config_value.model}</div>
                </div>
                <div>
                  <div className="text-sm text-gray-500">响应时间</div>
                  <div className="font-medium">{testResult.duration}ms</div>
                </div>
              </div>

              {testResult.success ? (
                <div className="space-y-4">
                  <div>
                    <Label className="text-sm font-medium text-gray-700 mb-2 block">
                      AI响应内容
                    </Label>
                    <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                      <p className="text-gray-800 whitespace-pre-wrap">
                        {testResult.response.text}
                      </p>
                    </div>
                  </div>

                  {testResult.response.usage && (
                    <div>
                      <Label className="text-sm font-medium text-gray-700 mb-2 block">
                        Token使用情况
                      </Label>
                      <div className="grid grid-cols-3 gap-4">
                        <div className="text-center p-3 bg-gray-50 rounded-lg">
                          <div className="text-sm text-gray-500">输入Token</div>
                          <div className="text-lg font-bold text-gray-800">
                            {testResult.response.usage.prompt_tokens}
                          </div>
                        </div>
                        <div className="text-center p-3 bg-gray-50 rounded-lg">
                          <div className="text-sm text-gray-500">输出Token</div>
                          <div className="text-lg font-bold text-gray-800">
                            {testResult.response.usage.completion_tokens}
                          </div>
                        </div>
                        <div className="text-center p-3 bg-gray-50 rounded-lg">
                          <div className="text-sm text-gray-500">总Token</div>
                          <div className="text-lg font-bold text-gray-800">
                            {testResult.response.usage.total_tokens}
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                <Alert className="border-red-200 bg-red-50">
                  <AlertCircle className="h-4 w-4 text-red-600" />
                  <AlertDescription className="text-red-800">
                    <strong>错误信息:</strong> {testResult.error}
                  </AlertDescription>
                </Alert>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Available Configs Info */}
      {llmConfigs.length === 0 && (
        <Alert>
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>
            没有找到活跃的大模型配置。请先在"大模型配置"页面添加并启用至少一个配置。
          </AlertDescription>
        </Alert>
      )}
    </div>
  );
}
